<?php
namespace app\api\model;

use think\Db;

class CouponModel
{
    /**
     * 单例模式
     * @return CouponModel
     *
     */
    public static function instance(){
        static $m = null;
        if(!$m){
            $m = new CouponModel();
        }
        return $m;
    }
    /**
     * 优惠券列表
     */
    public function couponlist($bid){
        $list = Db::name('couponAdd')
            ->field('starttime,commid,goodsid,bid,endtime,money,full_money,disid,type,status')
            ->where('bid',$bid)
	->where('status',0)
            ->where('starttime','<=',time())
            ->where('endtime','>=',time())
            ->select();
        foreach($list as $key=>&$val){
            if($val['type'] == 2){
                $comm = Db::name('commType')->field('name,ptid')->where('ptid',$val['commid'])->find();
                $val['form'] = $comm['name'];
            }
            if($val['type'] == 3){
                $comm = Db::name('goodsid')->field('name')->where('goodsid',$val['goodsid'])->find();
                $val['form'] = $comm['name'];
            }
        }
        return $list;

    }
    /**
     * 领取优惠券
     */
    public function getcoupon($disid,$uid){
        $couadd = Db::name('couponAdd')->field('number,money,endtime')->where('disid',$disid)->find();
        $count = Db::name('coupon')->where(['uid'=>$uid,'disid'=>$disid])->count();
        if(($couadd['number'] - $count) > 0){
            $arr = [];
            for($i=0;$i<4;$i++){
                $arr[] = randCode(6,0);
            }
            $data['ctitle'] = implode('-',$arr);
            $data['uid'] = $uid;
            $data['disid'] = $disid;
            $data['money'] = $couadd['money'];
            $data['createtime'] = time();
            $data['pasttime'] = $couadd['endtime'];
            $result = Db::name('coupon')->insert($data);
            return [$result,''];
        }else{
            return [false,6001];
        }
    }

}
